//  对ADG714芯片进行配置，可以按照下面两种方式进行
//  1) 从配置文件中读取参数之后进行配置: adg714_cfg adg714_cfg.ini
//  2) 对单个参数的配置: adg714_cfg pName pValue
//
//	update@2022-02-06: 原先设计的第二种使用方式不太合理,因为该程序每次对ADG进行配置时,
//		实际上是一次发送8个bits的数据,对ADG714的8个输出端口同时配置.因此,第二种使用方式
//		将不再使用!

#include "SchmidtCAM.h"

int main( int argc, char *argv[] ){

    int has_cfg = 0;
    int has_p_and_v = 0;
	
	if( argc == 2 ){
	    has_cfg = 1;
	} else if( argc == 3 ){
	    has_p_and_v = 1;
	    printf("##### This option of usage (argc == 3) id deprecated!\n");
	    return 0;
	}
	
	if( (has_cfg == 0) && (has_p_and_v == 0) ){
	    printf("usage:\n");
	    printf("\t%s adg714_cfg.ini\n", argv[0]);
	    printf("or\n");
	    printf("\t%s pName pValue\n", argv[0]);
	    return 0;
	}

	int fd = open("/dev/mem", O_RDWR | O_SYNC);
	uint *ptr1 = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, ADDR_GPIO_OUT);
	uint *gpio_reg 		= ptr1;		// 0x41200000
	uint *gpio2_reg		= ptr1+2;	// 0x41200008
	
	uint *ptr2 = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, ADDR_GPIO_IN);
	uint *gpio_in_reg	= ptr2;		// 0x41210000
	
	// SPI config
    SPI_CONFIG *spi_config = (SPI_CONFIG*)malloc(sizeof(SPI_CONFIG));
    setup_SPI_by_device_name( spi_config, "adg714" );
	
	ADG714_Config *adg714_cfg = (ADG714_Config*)malloc(sizeof(ADG714_Config));

	init_adg714_config( adg714_cfg );

	if( has_cfg == 1 ){
	    char inifile[1024];
	    sprintf(inifile, "%s", argv[1]);
	    read_adg714_config( adg714_cfg, inifile, "ADG714" );
	}

	if( has_p_and_v == 1 ){
	    char pName[16];
	    sprintf(pName, "%s", argv[1]);
	    int pValue = atoi(argv[2]);
	    update_adg714_config( adg714_cfg, pName, pValue );
	}
	
	print_adg714_config( adg714_cfg );

	config_adg714_via_SPI( gpio_reg, 
					       gpio2_reg, 
					       gpio_in_reg,
					       spi_config,
					       adg714_cfg );
    
    free(adg714_cfg);
    free(spi_config);
    
    munmap(ptr1,10);
    munmap(ptr2,10);
    close(fd);

    return 0;
}
